--[[

LysAutoRun

Addon to automatically run macros upon entering the game world.

]]

LAR_MAXLOOPS = 20;

function LAR_SF_StringSplit(inputString, seperatorChar)
	if ((inputString == nil) or (seperatorChar == nil)) then
		DEFAULT_CHAT_FRAME:AddMessage("Error: inputSting and/or seperatorChar is nil!", 1.0, 0.2, 0.2);
		return nil;
	end

	local outputTable = {};
	local tableIndex	= 1;
	local startLoc	= 1;
	local searchByte	= string.byte(seperatorChar, 1);

	for stringIndex = 1, string.len(inputString) do
		local stringByte = string.byte(inputString, stringIndex);
		if (stringByte == searchByte) then
			outputTable[tableIndex] = string.sub(inputString, startLoc, stringIndex);
			tableIndex = tableIndex + 1;

			startLoc = stringIndex + 1;
		end
	end

	return outputTable;
end

function LAR_RunMacros()
	local index = 1;
	local macroIndex = GetMacroIndexByName("LAR_Macro"..index);
	while (macroIndex ~= 0) do
		local name, texture, macroBody, macroLocal = GetMacroInfo(macroIndex);

		-- Split the macro into it's various component action lines
		macroCommands = LAR_SF_StringSplit(macroBody, string.char(10));

		-- If we have lines to process, do so
		if (macroCommands ~= nil) then
			-- Iterate through all macro command lines
			for macroLine = 1, table.getn(macroCommands) do
				local commandString = macroCommands[macroLine];
				local _;

				-- Check to see if macro line starts with /script, if so pull that as RunScript won't run the command with that in front.
				if (string.find(commandString, "/script") ~= nil) then
					_, _, commandString = string.find(commandString, "/script%s(.*)");
				end
				RunScript(commandString);
			end
		end

		index = index + 1;
		if (index ~= LAR_MAXLOOPS) then
			macroIndex = GetMacroIndexByName("LAR_Macro"..index);
		else
			macroIndex = nil;
		end
	end
end

------------------------------------------------------------------------------------------------
-- Core Program Functions - this program can't run without these.
------------------------------------------------------------------------------------------------
function LAR_OnLoad(frame)
	-- Register the variables loaded event...
	frame:RegisterEvent("ADDON_LOADED");
	frame:RegisterEvent("PLAYER_ENTERING_WORLD");
end

function LAR_OnEvent(frame, event, ...)
	if ((event == "ADDON_LOADED") and (select(1, ...) == "LysAutoRun")) then
		DEFAULT_CHAT_FRAME:AddMessage(LAR_VERSION.." loaded.");
		return;

	elseif (event == "PLAYER_ENTERING_WORLD") then
		LAR_RunMacros();
		return;

	end
end
